package com.example.weiwing.home.person;


import static android.app.Activity.RESULT_OK;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.bumptech.glide.Glide;
import com.example.weiwing.EditProfileActivity;
import com.example.weiwing.config.WeiWingConfig;
import com.example.weiwing.R;
import com.example.weiwing.entity.User;
import com.example.weiwing.home.HomeActivity;
import com.example.weiwing.home.study.CutFileUploadActivity;
import com.example.weiwing.util.CircleImageView;
import com.example.weiwing.util.SpUtils;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import java.util.List;


public class PersonFragment extends Fragment {

    private View view;
    public Handler mHandler;
    private Button btn_edit;
    private User user;
    private TextView tv_nickName;
    private TextView tv_signature;
    private TextView tv_uid;
    private TextView tv_following;
    private TextView tv_followers;
    private CircleImageView iv_avatar;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_person, container, false);
        btn_edit = view.findViewById(R.id.editButton);

        tv_nickName = view.findViewById(R.id.tv_nickName);
        tv_signature = view.findViewById(R.id.tv_signature);
        tv_uid = view.findViewById(R.id.tv_uid);
        tv_following = view.findViewById(R.id.tv_following);
        tv_followers = view.findViewById(R.id.tv_followers);
        iv_avatar = view.findViewById(R.id.iv_avatar);

        btn_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (user != null) {
                    Intent it = new Intent(view.getContext(), EditProfileActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("user", user);
                    it.putExtra("data", bundle);
                    startActivityForResult(it, 100);
                } else {
                    Toast.makeText(getActivity(), "请检查网络", Toast.LENGTH_SHORT).show();
                }
            }
        });

        new GetInfoThread().start();

        return view;
    }

    public class GetInfoThread extends Thread {
        @Override
        public void run() {
            HttpRequest.build(getActivity(), WeiWingConfig.getUrl() + "/user/getUserInfo")
                    .setAsync(false)
                    .addHeaders("token", SpUtils.getString(getActivity(), "token"))
                    .setResponseListener(new ResponseListener() {
                        @Override
                        public void onResponse(String response, Exception error) {
                            if (error == null) {
                                JSONObject jsonObject = JSON.parseObject(response);
                                if (jsonObject.getInteger("code") == 200) {
                                    user = jsonObject.getObject("data", new TypeReference<User>() {
                                    });
                                    refresh();
                                } else {
                                    // TODO:请求失败！
                                }

                            } else {
                                Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }).doGet();
        }
    }

    ;

    public void refresh() {

        tv_nickName.setText(user.getNickName());
        tv_signature.setText(user.getSignature());
        tv_uid.setText(user.getUserName());
        tv_following.setText(String.valueOf(user.getFollowing()));
        tv_followers.setText(String.valueOf(user.getFollowers()));
        Picasso.get().load(WeiWingConfig.getUrl() + user.getAvatar())
                .placeholder(R.mipmap.yavatar)
                .transform(getTransformation(iv_avatar))
                .fit()
                .into(iv_avatar);
    }

    public static Transformation getTransformation(final ImageView imageView) {
        return new Transformation() {

            @Override
            public Bitmap transform(Bitmap source) {
                int targetWidth = imageView.getMaxWidth();
                if (source.getWidth() == 0) {
                    return source;
                }
                //如果图片大小大于等于设置的宽度，则按照设置的宽度比例来缩放
                double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
                int targetHeight = (int) (targetWidth * aspectRatio);
                if (targetWidth >= source.getWidth()) {
                    return source;
                }
                if (targetHeight != 0 && targetWidth != 0) {
                    Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
                    if (result != source) {
                        // Same bitmap is returned if sizes are the same
                        source.recycle();
                    }
                    return result;
                } else {
                    return source;
                }
            }

            @Override
            public String key() {
                return "transformation" + " desiredWidth";
            }
        };
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            new GetInfoThread().start();
        }
    }
}
